package com.flower.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.flower.model.entity.PageQuery;
import com.flower.model.entity.Product;
import com.flower.result.PageResult;
import com.flower.result.Result;
import com.flower.service.ProductsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@SuppressWarnings("all")
/**
 *@ClassName ProductsController
 *@Description TODO
 *@Author @O_o  GW__
 *@Date 2025/6/10 14:54
 *@Version 1.0
 */
@RestController
@Slf4j
@RequestMapping("/product")
@Api(tags = "商品管理")
public class ProductsController {
    @Autowired
    private ProductsService productsService;
    @GetMapping("/")
    @ApiOperation("查询商品列表")
    public Result getProducts() {
        log.info("查询商品列表");
        List<Product> products = productsService.getProducts();
        return Result.success(products);
    }

    @GetMapping("/id/{id}")
    @ApiOperation("查询商品详情")
    public Result<Product> getProduct(@PathVariable Integer id) {
        log.info("查询商品详情");
        Product product = productsService.getProduct(id);
        return Result.success(product);
    }
    @GetMapping("/page")
    @ApiOperation("分页查询商品列表")
    public Result<PageResult> getProducts(PageQuery PageQuery) {
        PageResult pageResult = productsService.pageQuery(PageQuery);
        return Result.success(pageResult);
    }
    @GetMapping("/page1")
    @ApiOperation("库存管理")
    public Result<PageResult> getProductsManage(PageQuery PageQuery) {
        PageResult pageResult = productsService.pageQuery(PageQuery);
        return Result.success(pageResult);
    }

    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response)throws Exception{
        List<Product> list = productsService.list();
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id","编号");
        writer.addHeaderAlias("name","商品名称");
        writer.addHeaderAlias("psort","所属类别");
        writer.addHeaderAlias("proCost","进价");
        writer.addHeaderAlias("proPrice","售价");
        writer.addHeaderAlias("proStock","库存");
        writer.addHeaderAlias("proFrom","供应商");
        writer.addHeaderAlias("proSales","销量");
        //一次性写出list内的对象到Excel，使用默认样式，强制输出标题
        writer.write(list,true);
        //设置浏览器响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("商品信息","UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }
    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception{
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //方式二：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<Product> products = CollUtil.newArrayList();
        for (List<Object> row : list){
            Product product=new Product();
            product.setName(row.get(0).toString());
            product.setPsort(row.get(1).toString());
            product.setProCost(Double.valueOf(row.get(2).toString()));
            product.setProPrice(Double.valueOf(row.get(3).toString()));
            product.setProStock(Integer.valueOf(row.get(4).toString()));
            product.setProFrom(row.get(5).toString());
            product.setProSales(Integer.valueOf(row.get(6).toString()));
            products.add(product);
        }
        productsService.saveBatch(products);//插入数据库
        return Result.success(true);
    }
}
